package com.example.treehole.ui.component

import android.annotation.SuppressLint
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChatBubble
import androidx.compose.material.icons.filled.ChatBubbleOutline
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.treehole.LocalNavController
import com.example.treehole.LocalPostDetailViewModel
import com.example.treehole.LocalUserViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.model.PostInfo
import com.example.treehole.ui.theme.Cyan
import com.example.treehole.ui.theme.iconBlue
import com.example.treehole.ui.theme.postCyan
import kotlinx.coroutines.launch
import java.util.Locale

@SuppressLint("UnrememberedMutableInteractionSource")
@Composable
fun PostCard(
    post: PostInfo,
    isPopularCard: Boolean = false,
    popularRank: Int = 0,
) {
    val navController = LocalNavController.current
    val userViewModel = LocalUserViewModel.current
    val userId by userViewModel.userId.collectAsState()
    val jwlToken by userViewModel.jwlToken.collectAsState()
    val scope = rememberCoroutineScope()

    val postDetailViewModel = LocalPostDetailViewModel.current

    val timeText = formatTime(post.createDate)
    val isLike = remember { mutableStateOf(post.isLike) }
    val isFavorite = remember { mutableStateOf(post.isFavorite) }
    val likeCount = remember { mutableIntStateOf(post.likeCount) }
    val favoriteCount = remember { mutableIntStateOf(post.favoriteCount) }

    val formatPostId = String.format(Locale.PRC, "#%08d", post.postId)

    Card(
        modifier =
        Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .border(1.dp, Color.Gray)
            .clickable(
                onClick = {
                    navController.navigate("postDetail")
                    scope.launch {
                        userId?.let {
                            postDetailViewModel.getPostDetail(
                                jwlToken,
                                post.postId,
                                it
                            )
                        }
                    }
                }
            ),
        colors = CardDefaults.cardColors(containerColor = postCyan),
        shape = RectangleShape,
        elevation = CardDefaults.cardElevation(4.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clip(RoundedCornerShape(0.dp)),
        ) {
            if (isPopularCard)
                Text(
                    text = "$popularRank",
                    modifier =
                    Modifier
                        .padding(start = 8.dp, top = 2.dp)
                        .align(Alignment.TopStart),
                    fontSize = 80.sp,
                    fontWeight = FontWeight.Bold,
                    color = Cyan
                )
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp, horizontal = 12.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = post.title,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        style = MaterialTheme.typography.headlineSmall,
                        modifier = Modifier.weight(1f)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = formatPostId, color = Color.Gray)
                }
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = post.content, maxLines = 3, overflow = TextOverflow.Ellipsis) //
                Spacer(modifier = Modifier.height(8.dp))
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical =  8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 时间显示在前面
                    Text(text = timeText, modifier = Modifier.weight(1f), color = Color.Gray)
                    // 三个图标显示在后面
                    Row(
                        modifier = Modifier
                            .weight(2f)
                            .fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceEvenly
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            IconButton(
                                onClick = {
                                    scope.launch {
                                        userId?.let {
                                            if (isLike.value && DataRepository.unlikePost(
                                                    jwlToken,
                                                    post.postId,
                                                    it
                                                ) ||
                                                (!isLike.value && DataRepository.likePost(
                                                    jwlToken,
                                                    post.postId,
                                                    it
                                                ))
                                            ) {
                                                likeCount.intValue += if (isLike.value) -1 else 1
                                                isLike.value = !isLike.value
                                                post.isLike = isLike.value
                                                post.likeCount = likeCount.intValue
                                            }
                                        }
                                    }
                                },
                                modifier = Modifier.size(24.dp)
                            ) {
                                Icon(
                                    imageVector =
                                    if (isLike.value) Icons.Default.Favorite
                                    else Icons.Default.FavoriteBorder,
                                    contentDescription = "Likes",
                                    tint = iconBlue,
                                    modifier = Modifier.size(24.dp)
                                )
                            }

                            Spacer(modifier = Modifier.width(5.dp))
                            Text(
                                text = numberTransfer(likeCount.intValue),
                                modifier = Modifier.width(48.dp)
                            )
                        }
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            Icon(
                                imageVector =
                                if (post.isComment) Icons.Default.ChatBubble
                                else Icons.Default.ChatBubbleOutline,
                                contentDescription = "Comments",
                                tint = iconBlue
                            )
                            Spacer(modifier = Modifier.width(5.dp))
                            Text(
                                text = numberTransfer(post.commentCount),
                                modifier = Modifier.width(48.dp)
                            )
                        }
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            IconButton(
                                onClick = {
                                    scope.launch {
                                        userId?.let {
                                            if (isFavorite.value && DataRepository.unfavoritePost(
                                                    jwlToken,
                                                    post.postId,
                                                    it
                                                ) ||
                                                (!isFavorite.value && DataRepository.favoritePost(
                                                    jwlToken,
                                                    post.postId,
                                                    it
                                                ))
                                            ) {
                                                favoriteCount.intValue += if (isFavorite.value) -1 else 1
                                                isFavorite.value = !isFavorite.value
                                                post.isFavorite = isFavorite.value
                                                post.favoriteCount = favoriteCount.intValue
                                            }
                                        }
                                    }
                                },
                                modifier = Modifier.size(24.dp)
                            ) {
                                Icon(
                                    imageVector =
                                    if (isFavorite.value) Icons.Default.Star
                                    else Icons.Default.StarBorder,
                                    contentDescription = "Favorites",
                                    tint = iconBlue
                                )
                            }
                            Spacer(modifier = Modifier.width(5.dp))
                            Text(
                                text = numberTransfer(favoriteCount.intValue),
                                modifier = Modifier.width(48.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}
